import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Table,
  Space,
  Image,
  Tag,
  Popconfirm,
  message
} from 'antd'
import { Link, useHistory } from 'react-router-dom'
import styles from './index.module.scss'
import { useEffect, useRef } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getArticle, delArticle } from '@/store/actions/article'
import { DeleteOutlined, EditOutlined } from '@ant-design/icons'

import defaultImg from '@/assets/error.png'
import { ARTICLE_STATUS, ARTICLE_STATUS_MAP } from '@/constant'
import Channel from '@/components/Channel'
const { RangePicker } = DatePicker

export default function Article () {
  const history = useHistory()
  // 表单查询
  // 在多次渲染之间 保持查询条件数据
  const refParams = useRef({})
  const dispatch = useDispatch()

  useEffect(() => {
    // 获取文章信息
    dispatch(getArticle({ page: 1 }))
  }, [])

  const {
    results: dataSource,
    total_count: total,
    page: current,
    per_page: pageSize
  } = useSelector((state) => state.article)
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      key: 'name',
      render (obj) {
        if (obj.type > 0) {
          return (
            <Image
              width={180}
              fallback={defaultImg}
              height={120}
              src={obj.images[0]}
            />
          )
        } else {
          return <Image width={180} height={120} src={defaultImg} />
        }
      }
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: function (status) {
        // const res = ARTICLE_STATUS.find((it) => it.id === status)
        const res = ARTICLE_STATUS_MAP[status]
        if (res) {
          return <Tag color={res.color}>{res.title}</Tag>
        }
      }
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
      key: 'pubdate'
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
      key: 'read_count'
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
      key: 'comment_count'
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
      key: 'like_count'
    },
    {
      title: '操作',
      key: 'op',
      dataIndex: 'cover',
      render (obj, row, index) {
        // console.log(obj, row, index)
        return (
          <Space>
            <Button
              onClick={() => history.push('/home/publish/' + row.id)}
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
            />

            <Popconfirm title="确认要删除吗?" onConfirm={() => onDel(row.id)}>
              <Button
                type="primary"
                shape="circle"
                danger
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Space>
        )
      }
    }
  ]

  const onFinish = ({ status, channel_id: channelId, dateRange }) => {
    const params = refParams.current
    // 1.类型。 如果 类型 不是全部，就传给后端参数
    if (status !== -1) {
      params.status = status
    }

    // 2. 频道
    params.channel_id = channelId

    // 3. 日期区间
    console.log('日期区间', dateRange)
    if (dateRange) {
      params.begin_pubdate = dateRange[0]
        .startOf('day')
        .format('YYYY-MM-DD HH-mm-ss')
      params.end_pubdate = dateRange[1]
        .endOf('day')
        .format('YYYY-MM-DD HH-mm-ss')
    }

    console.log('组装的参数是', params)

    dispatch(getArticle(params))
  }

  // 表格分页
  const onChange = (page, pageSize) => {
    const params = refParams.current
    console.log('表格分页', params, page)
    // 重发请求，在整体条件的基础上，设置page
    params.page = page
    dispatch(getArticle(params))
  }

  // 删除
  const onDel = async (id) => {
    try {
      // 根据id去做删除
      console.log(id)
      await dispatch(delArticle(id))
      message.success('删除成功', 0.3)
      // 重新获取数据
      dispatch(getArticle(refParams.current))
    } catch (err) {
      console.log(err)
      message.error(err.response.message, 0.5)
    }
  }
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }>
        <Form onFinish={onFinish} initialValues={{ status: -1, channel_id: 4 }}>
          <Form.Item label="状态" name="status">
            <Radio.Group>
              {ARTICLE_STATUS.map((it) => (
                <Radio key={it.id} value={it.id}>
                  {it.title}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            <Channel />
          </Form.Item>

          <Form.Item label="日期" name="dateRange">
            <RangePicker />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Card title={`根据筛选条件共查询到${total}条结果:`} style={{ marginTop: 10 }}>
        <Table
          pagination={{ total, onChange, pageSize, current }}
          rowKey="id"
          dataSource={dataSource}
          columns={columns}
        />
      </Card>
    </div>
  )
}
